import UIKit
import Kingfisher

class ContactVC: ChatBaseController {
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: self.view.frame, style: .plain)
        tableView.separatorStyle = .singleLine
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(ContactCell.self, forCellReuseIdentifier: ContactCell.contactCellId)
        tableView.rowHeight = 55
//        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        
        //设置索引的字体颜色 (默认是蓝色)
//        tableView.sectionIndexColor = UIColor.black.withAlphaComponent(0.6)   //可以改变索引字体的颜色
        
        return tableView
    }()
    
    lazy var tablefootview:UIView = {
        let tablefootview = UIView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 55))
        return tablefootview
    }()
    
    lazy var bottomLabel: UILabel = {
        let label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 18)
        label.textColor = UIColor.lightGray
//        label.backgroundColor = UIColor.white
        return label
    }()
    
    lazy var footviewlineview: UIView = {
        let footviewlineview = UIView()
//        footviewlineview.backgroundColor = UIColor.white
        return footviewlineview
    }()
    
    var contactList = [ChatContact]()
    let collation = UILocalizedIndexedCollation.current()
    var sectionsArray: [[ChatContact]] = [[ChatContact]]()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.title = "通讯录"
        self.view.addSubview(tableView)
        
        tablefootview.addSubview(footviewlineview)
        tablefootview.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(footviewlineview.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
//        footviewlineview.snp.makeConstraints { (make) in
//            make.top.equalToSuperview()
//            make.left.right.equalToSuperview()
//            make.height.equalTo(1)
//        }
        bottomLabel.text = "\(self.contactList.count)位联系人"
        self.tableView.tableFooterView = tablefootview
    }
    let service = ContactService()
    
    func loadData() {
        DispatchQueue.global().async {
            self.contactList = self.service.getContactList()
            if self.contactList.count > 0 {
                self.setSection()
                DispatchQueue.main.async {
                    self.bottomLabel.text = "\(self.contactList.count)位联系人"
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    @objc func buttonTap(button:UIButton) {
        self.tabBarController?.navigationController?.popViewController(animated: true)
    }
    
    func setSection(){
        //        self.collation = UILocalizedIndexedCollation.current()
        let sectionTitlesCount = self.collation.sectionTitles.count
        print(sectionTitlesCount)
        //临时数据，存放section对应的userObjs数组数据
        var newSectionsArray = [[ChatContact]]()
        
        //设置sections数组初始化：元素包含userObjs数据的空数据
        for _ in 0 ..< sectionTitlesCount {
            let array = [ChatContact]()
            newSectionsArray.append(array)
        }
        
        //将用户数据进行分类，存储到对应的sesion数组中
        
        for contact in contactList {
            //根据timezone的localename，获得对应的的section number
            let sectionNumber = self.collation.section(for: contact, collationStringSelector: #selector(getter: ChatContact.displayName))
            _ = self.collation.sectionTitles[sectionNumber]
            //            if !indexArray.contains(headerString) {
            //                indexArray.append(headerString)
            //            }
            //
            //获得section的数组
            var sectionBeans = newSectionsArray[sectionNumber]
            
            //添加内容到section中
            sectionBeans.append(contact)
            
            // swift 数组是值类型，要重新赋值
            newSectionsArray[sectionNumber] = sectionBeans
        }
        
        //排序，对每个已经分类的数组中的数据进行排序，如果仅仅只是分类的话可以不用这步
        for i in 0 ..< sectionTitlesCount {
            let beansArrayForSection = newSectionsArray[i]
            //获得排序结果
            let sortedBeansArrayForSection = collation.sortedArray(from: beansArrayForSection, collationStringSelector:  #selector(getter: ChatContact.displayName))
            //替换原来数组
            newSectionsArray[i] = sortedBeansArrayForSection as! [ChatContact]
            
        }
        
        sectionsArray = newSectionsArray
    }
}

extension ContactVC:UITableViewDataSource, UITableViewDelegate {
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.contactCellId, for: indexPath) as! ContactCell
        let chatContact = sectionsArray[indexPath.section][indexPath.row]
        
        cell.selectionStyle = .none
        cell.nameLabel.text = chatContact.displayName
        cell.headimage.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(chatContact.avatar ?? "unknown")!), placeholder: UIImage.init(named:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        cell.tagbutton.isHidden = true
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.collation.sectionTitles.count
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if sectionsArray.count <= 0 {
            return nil
        } else {
            let beanInSection = sectionsArray[section]
            if beanInSection.count == 0 {
                return nil
            }else {
                let customview = UIView.init(frame: CGRect.init(x: 10, y: 0, width: UIScreen.main.bounds.size.width, height: 23))
                let label = UILabel.init(frame: CGRect.zero)
                label.backgroundColor = .systemBackground
                label.isOpaque = false
                label.font = UIFont.systemFont(ofSize: 13)
                label.frame = CGRect(x: 10, y: 0, width: 50, height: 23)
                if sectionsArray.count == 0 {
                    label.text = ""
                }
                let beansInSection = sectionsArray[section]
                if (beansInSection as AnyObject).count <= 0 {
                    label.text = ""
                }
                let headerString = collation.sectionTitles[section]
                label.text = headerString
                customview.addSubview(label)
                customview.backgroundColor = .systemBackground
                return customview
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if sectionsArray.count <= 0 {
            return 0
        } else {
            let beanInSection = sectionsArray[section]
            if beanInSection.count == 0 {
                return 0
            }
            return 23;
        }
    }
    
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        var temparry = [String]()
        for i in 0..<collation.sectionTitles.count {
            
            temparry.append(collation.sectionTitles[i])
        }
        temparry.insert("★", at: 0)
        return temparry
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return collation.section(forSectionIndexTitle: index)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionsArray.count == 0 {
            return 0
        }
        let beanInSection = sectionsArray[section]
        return beanInSection.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let session = sectionsArray[indexPath.section][indexPath.row]
        let chatvc = ChatVC()
        chatvc.title = session.displayName
        chatvc.chatType = ChatType.p2p
        chatvc.sessionServerId = session.userId
        chatvc.sessionName = session.displayName
        chatvc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(chatvc, animated: true)
    }
}


